package com.sykj.web;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sykj.model.User;
import com.sykj.service.UserService;

@Controller
@RequestMapping("/shiro")
public class ShiroController {
	@Autowired
	UserService userService;

	@RequestMapping("/login")
	public String login(String username, String password) {
		Subject currentUser = SecurityUtils.getSubject();
		System.out.println("执行登录");
		if (!currentUser.isAuthenticated()) {
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			// 记住我
//			token.setRememberMe(true);
			try {
				// 登录
				currentUser.login(token);
				System.out.println("登录成功！" );
				return "success"; // 登录成功跳转成功页面
			} catch (AuthenticationException ae) {
				System.out.println("登录失败" + ae.getMessage());
				return "login"; //登录失败跳转登录页面
			}
		}
		return "success";
	}
	
	
	/**
	 * 用户注册
	 * @return
	 */
	@RequestMapping("/register") 
	public String register(User user, Model model) {
		System.out.println("执行用户注册" + user.getName() + ", 密码" + user.getPassword());
		
		return "login";
		
	}
	
	@RequestMapping("/logout")
	public String logout() {
		Subject currentUser = SecurityUtils.getSubject();
		System.out.println("当前登录状态：" + currentUser.isAuthenticated());
		
		return "login";
	}
}
